package com.zhou.framework.util;

import com.zhou.framework.common.SpringFactory;
import com.zhou.framework.quartz.dao.QuartzLog;
import com.zhou.framework.quartz.service.QuartzLogService;
import com.zhou.util.AddressUtil;
import com.zhou.framework.config.DbSettingConfig;
import com.zhou.framework.config.SystemConfig;
import com.zhou.framework.dao.Log;
import com.zhou.framework.pool.DefaultThreadPool;
import com.zhou.org.service.LogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

/**
 * @author lang.zhou
 * @since 2023/2/19
 */
@Slf4j
@Configuration
public class ThreadPoolManager {

    private static DefaultThreadPool pool ;
    private static long delay = 10L;

    public ThreadPoolManager(DefaultThreadPool pool, DbSettingConfig config) {
        delay = config.getLong("thread-pool","delay",10L);
        ThreadPoolManager.pool = pool;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public static void execute(TimerTask task) {
        pool.schedule(task, delay, TimeUnit.MILLISECONDS);
    }
    public static void saveLog(Log l) {
        execute(new TimerTask() {
            @Override
            public void run() {
                try{
                    if(SystemConfig.getInstance().isLocation()){
                        l.setLocation(AddressUtil.getRealAddressByIP(l.getIp()));
                    }
                    LogService bean = SpringFactory.getBean(LogService.class);
                    bean.saveLog(l);
                }catch (Exception e){
                    log.error("",e);
                }
            }
        });
    }

    public static void saveQuartzLog(QuartzLog l) {
        execute(new TimerTask() {
            @Override
            public void run() {
                try{
                    QuartzLogService service = SpringFactory.getBean(QuartzLogService.class);
                    service.saveLog(l);
                }catch (Exception e){
                    log.error("",e);
                }
            }
        });
    }
}
